<template>
  <div class="rescue-container">
    <!-- 顶部控制栏 -->
    <div class="control-bar">
      <!-- <el-button size="small" type="danger" circle>
        <i class="icon el-icon-bell"></i>
      </el-button> -->

      <div class="patient-info">
        <span class="patient-id">{{ patCur?.bedNumber ? patCur.bedNumber : '--' }}</span>
        <span class="patient-name"> {{ patCur?.patientName ? patCur.patientName : '--' }}</span>
        <span class="patient-sex">{{ gender || '--' }}</span>
        <span class="patient-age">{{ patCur?.age ? patCur.age + '岁' : '--' }}</span>
      </div>

      <div class="time-control">
        <span>抢救开始时间:</span>
        <el-date-picker
          v-model="rescueStartTime"
          type="datetime"
          placeholder=""
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
        />

        <span>采集频率:</span>
        <!-- :disabled="!isRescuing" -->
        <el-select
          v-model="collectionFrequency"
          placeholder="请选择"
          style="width: 100px"
          @change="handleFrequencyChange"
        >
          <el-option label="10秒" value="10" />
          <el-option label="30秒" value="30" />
          <el-option label="1分钟" value="60" />
          <el-option label="5分钟" value="300" />
        </el-select>
        <span>/次</span>

        <span class="timer" :style="{ color: isRescuing ? '#FF0000' : '#999' }">
          {{ currentTime }}
        </span>
      </div>

      <div class="action-buttons">
        <el-button v-if="isRescuing" size="small" type="danger" @click="toggleRescueMode">
          <i class="el-icon-video-pause icon"></i>
          退出抢救
        </el-button>

        <el-button
          v-else
          size="small"
          :type="isRescuing ? 'primary' : 'danger'"
          @click="toggleRescueMode"
        >
          <i class="icon" :class="isRescuing ? 'el-icon-video-pause' : 'el-icon-video-play'"></i>
          抢救开始
        </el-button>

        <!-- <el-button size="small" class="history-btn" @click="lishi"
          >历史记录</el-button
        > -->
        <el-button size="small" class="history-btn" @click="openLishi">打开历史记录</el-button>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 视图切换 -->
      <div class="view-switch">
        <el-radio-group v-model="activeView" size="small">
          <el-radio-button label="chart">趋势图</el-radio-button>
          <el-radio-button label="table">表格</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 趋势图 -->
      <div v-show="activeView === 'chart'" class="chart-area">
        <div ref="chartContainer" class="chart-container"></div>
      </div>

      <!-- 表格 -->
      <div v-show="activeView === 'table'" class="table-area">
        <el-table stripe :data="vitalData" border size="small" style="width: 100%">
          <el-table-column prop="createTime" label="时间" width="100"></el-table-column>
          <el-table-column prop="ecg" label="HR"></el-table-column>
          <el-table-column prop="rr" label="RR"></el-table-column>
          <el-table-column prop="spo2" label="SPO2"></el-table-column>
          <el-table-column prop="ibpS" label="ibpS"></el-table-column>
          <el-table-column prop="ibpD" label="ibpD"></el-table-column>
          <el-table-column prop="nibpS" label="NibpS"></el-table-column>
          <el-table-column prop="nibpD" label="NibpD"></el-table-column>
        </el-table>
      </div>

      <!-- 右侧生命体征 -->
      <div class="vital-signs">
        <div class="vital-card">
          <div class="vital-name">HR</div>
          <div class="vital-value">{{ youData.ecg }}</div>
        </div>

        <div class="vital-card">
          <div class="vital-name">SPO2</div>
          <div class="vital-value">{{ youData.spo2 }}</div>
        </div>

        <div class="vital-card">
          <div class="vital-name">NIBP</div>
          <div class="vital-value">{{ youData.nibpS }}/{{ youData.nibpD }}</div>
        </div>

        <div class="vital-card">
          <div class="vital-name">IBP</div>
          <div class="vital-value">{{ youData.ibpS }}/{{ youData.ibpD }}</div>
        </div>
      </div>
    </div>

    <div class="operation-area">
      <!-- 措施按钮区 -->
      <div class="action-buttons">
        <div class="button-group">
          <div class="group-title">措施</div>
          <el-button
            v-for="action in emergencyActions"
            :key="action"
            size="small"
            @click="addActionOrMedicine(action)"
          >
            {{ action }}
          </el-button>
        </div>
      </div>

      <div class="action-buttons">
        <div class="button-group">
          <div class="group-title">用药</div>
          <el-button
            v-for="med in medications"
            :key="med"
            size="small"
            @click="addActionOrMedicine(med)"
          >
            {{ med }}
          </el-button>
        </div>
      </div>

      <div class="action-buttons">
        <div class="button-group">
          <div class="flexBox">
            <div class="group-titleSpe">操作记录</div>

            <span>
              <el-button v-if="flag" size="small" type="primary" @click="editPro">编辑</el-button>
              <el-button v-if="flag" size="small" @click="cancel">取消</el-button>

              <el-button v-else size="small" type="primary" @click="newAdd">新增</el-button>
            </span>
          </div>

          <div class="record-form">
            <div>时间</div>

            <el-date-picker
              v-model="rescueStartTime1"
              type="datetime"
              placeholder=""
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            />

            <div>项目</div>
            <el-input
              v-model="operationNote"
              type="textarea"
              :rows="2"
              placeholder=""
              size="small"
            ></el-input>
          </div>
        </div>
      </div>

      <!-- 操作记录区 -->
      <div class="record-area">
        <div class="records-list">
          <div class="record-header">
            <span>时间</span>
            <span>项目</span>
            <span>操作</span>
          </div>
          <div v-for="(record, index) in operationRecords" :key="index" class="record-item">
            <span class="record-time">
              {{ format(Number(record.recTime), 'yyyy-MM-dd HH:mm:ss') }}</span
            >
            <span class="record-action">{{ record.project }}</span>
            <span>
              <el-button type="text" size="small" @click="handleEdit(record)">编辑</el-button>
              <el-popconfirm title="确认删除？" @confirm="handleRecordDel(record)">
                <template v-slot:reference>
                  <el-button
                    v-if="permissionCheck()"
                    size="small"
                    type="text"
                    style="color: #f56c6c; margin-left: 20px"
                    >删除</el-button
                  >
                </template>
              </el-popconfirm>
            </span>
          </div>
          <div v-if="operationRecords.length === 0" class="empty-record">暂无记录</div>
        </div>
      </div>
    </div>

    <!-- 退出确认对话框 -->

    <el-dialog title="提示" v-model:visible="confirmDialogVisible">
      <span>是否退出抢救模式?</span>

      <el-dialog width="50%" title="" v-model:visible="innerVisible" append-to-body>
        <el-form ref="ruleFormRef" :model="form" :rules="rules">
          <el-form-item label="抢救原因" :label-width="formLabelWidth">
            <el-input v-model="form.reason" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="抢救结果" :label-width="formLabelWidth">
            <el-input v-model="form.result" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="抢救人" :label-width="formLabelWidth">
            <el-input v-model="form.rescuer" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="抢救结束时间" :label-width="formLabelWidth" prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder=""
              style="width: 100%"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <template v-slot:footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submit()">提交</el-button>
          </div>
        </template>
      </el-dialog>

      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">否</el-button>
          <el-button type="primary" @click="sure">是</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="历史记录" v-model:visible="dialogTableVisible" width="80%">
      <el-table :data="gridData">
        <el-table-column property="reason" label="抢救原因" width="150"></el-table-column>
        <el-table-column property="result" label="抢救原因" width="200"></el-table-column>
        <el-table-column property="rescuer" label="抢救人" width="200"></el-table-column>
        <el-table-column label="抢救结束时间" align="center" width="180">
          <template v-slot="scope">
            {{ formatTime(Number(scope.row.endTime), 'yyyy-MM-dd HH:mm:ss') }}
          </template>
        </el-table-column>

        <el-table-column v-slot="{ row, $index }" label="操作" align="center" width="100px">
          <el-button v-has="'chineseMedical:edit'" type="text" @click="bianji(row)">编辑</el-button>
          <el-popconfirm
            v-has="'chineseMedical:del'"
            title="确认删除？"
            style="margin-left: 6px"
            @confirm="handleDel(row)"
          >
            <template v-slot:reference>
              <el-button type="text" style="color: #f56c6c">删除</el-button>
            </template>
          </el-popconfirm>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog width="50%" title="" v-model:visible="innerVisible2" append-to-body>
      <el-form :model="form1">
        <el-form-item label="抢救原因" :label-width="formLabelWidth">
          <el-input v-model="form1.reason" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="抢救结果" :label-width="formLabelWidth">
          <el-input v-model="form1.result" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="抢救人" :label-width="formLabelWidth">
          <el-input v-model="form1.rescuer" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="抢救结束时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form1.endTime"
            type="datetime"
            placeholder=""
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit2">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { format } from 'date-fns'
import * as echarts from 'echarts'
import {
  computed,
  defineComponent,
  nextTick,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from 'vue'

// import {
//   addRescue,
//   collectHis,
//   delGeneral,
//   delRescue,
//   generalRecord,
//   getRescue,
//   modifyRescue,
//   queryGeneral,
//   queryHis,
//   saveGeneral,
//   saveHis,
// } from '@/api/nursing/nursingRecord'
//import { useDict, usePatCur } from '@/hooks'
import { formatTime } from '@/utils/format'
import { getElementFnFromInstance, getStoreFromInstance } from '@/utils/instance'

export default defineComponent({
  name: 'RescuePage',

  components: {},
  setup() {
    const chartContainer = ref(null)
    const chart = ref(null)
    const timer = ref(null)
    const dataUpdateInterval = ref(null)

    const state = reactive({
      dialogTableVisible: false,
      rules: {
        endTime: [
          {
            type: 'datetime',
            required: true,
            message: '请选择抢救结束时间',
            trigger: 'change',
          },
        ],
      },
      gridData: [],
      youData: [],
      Id: '',
      form: {
        reason: '',
        result: '',
        rescuer: '',
        endTime: '',
      },
      form1: {
        reason: '',
        result: '',
        rescuer: '',
        endTime: '',
      },
      formLabelWidth: '120px',

      innerVisible: false,
      innerVisible2: false,
      recordTime: +new Date(),
      flag: false,
      rowData: '',
      collectionFrequency: '60',
      // isRescuing: false,
      isRescuing: true,

      rescueStartTime: new Date(),
      rescueStartTime1: '',
      currentTime: '00:00:00',
      confirmDialogVisible: false,
      operationNote: '',
      operationRecords: [],

      activeView: 'chart',

      emergencyActions: [
        '胸外按压',
        '电除颤',
        '气管插管',
        '气管切开',
        '动脉穿刺',
        '静脉穿刺',
        '心包穿刺',
        '腹腔穿刺',
        '关节穿刺',
        '吸痰',
        '洗胃',
        '灌肠',
        '紧急开胸',
        '紧急开腹',
      ],
      medications: ['葡萄糖', '感冒灵'],
      vitalData: [],
      timePoints: [],
    })

    const initChart = () => {
      if (chartContainer.value && !chart.value) {
        chart.value = echarts.init(chartContainer.value)
        updateChart()
      }
    }

    const updateChart = () => {
      const option = {
        grid: {
          top: 20,
          right: 10,
          bottom: 30,
          left: 50,
        },
        legend: {
          data: ['HR', 'RR', 'SPO2', 'ibpS', 'ibpD', 'NibpS', 'NibpD'], // 需要与series中的name一一对应
          right: 10, // 距离右侧距离
          top: 0, // 距离顶部距离
          itemGap: 20, // 图例间隔
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: state.timePoints,
          axisLine: { lineStyle: { color: '#999' } },
        },
        yAxis: {
          type: 'value',
          splitLine: { lineStyle: { type: 'dashed' } },
        },
        series: [
          {
            name: 'HR',
            type: 'line',
            data: Array(state.timePoints.length).fill(0),
            smooth: true,
            lineStyle: { color: '#FF5252', width: 2 },
            symbol: 'circle',
            symbolSize: 8,
          },
          {
            name: 'RR',
            type: 'line',
            data: Array(state.timePoints.length).fill(0),
            smooth: true,
            lineStyle: { color: '#4CAF50', width: 2 },
            symbol: 'circle',
            symbolSize: 8,
          },
          {
            name: 'SPO2',
            type: 'line',
            data: Array(state.timePoints.length).fill(0),
            smooth: true,
            lineStyle: { color: '#2196F3', width: 2 },
            symbol: 'circle',
            symbolSize: 8,
          },
          {
            name: 'ibpS',
            type: 'line',
            data: Array(state.timePoints.length).fill(0),
            smooth: true,
            lineStyle: { color: '#9C27B0', width: 2 },
            symbol: 'circle',
            symbolSize: 8,
          },
          {
            name: 'ibpD',
            type: 'line',
            data: Array(state.timePoints.length).fill(0),
            smooth: true,
            lineStyle: { color: '#FF9800', width: 2 },
            symbol: 'circle',
            symbolSize: 8,
          },
          {
            name: 'NibpS',
            type: 'line',
            data: Array(state.timePoints.length).fill(0),
            smooth: true,
            lineStyle: { color: '#607D8B', width: 2 },
            symbol: 'circle',
            symbolSize: 8,
          },
          {
            name: 'NibpD',
            type: 'line',
            data: Array(state.timePoints.length).fill(0),
            smooth: true,
            lineStyle: { color: '#795548', width: 2 },
            symbol: 'circle',
            symbolSize: 8,
          },
        ],
      }
      if (chart.value) {
        chart.value.setOption(option, true) //true表示不合并选项
      }
    }

    //  const dict = useDict(['pat_sex'])
    // const store = getStoreFromInstance()
    // const patCur = computed(() => store.getters.patCur)
    // const user = computed(() => store.getters.user)
    // const roles = computed(() => store.getters.roles)
    const { $message } = getElementFnFromInstance()
    const shortName = computed(() => {
      if (user.value && user.value.name) {
        return user.value.name
      }
      return ''
    })
    //  const { zdIndex } = usePatCur()
    const gender = computed(() => {
      let str = '--'
      // if (patCur.value && dict.pat_sex) {
      //   const sex = dict.pat_sex.find((item) => Number(item.value) === patCur.value.gender)
      //   str = sex ? sex.label : str
      // }
      return str
    })

    function openLishi() {
      state.dialogTableVisible = true
      getList()
    }
    function getList() {
      const params = {
        // endTime: state.endTime,

        // startTime: state.startTime,
        hospitalNumber: patCur.value?.hospitalNumber,
        patientIdent: patCur.value?.patientIdent,
      }
      queryGeneral(params).then((res) => {
        state.gridData = res.data
      })
    }
    function handleDel(row) {
      delGeneral(row.id).then(() => {
        $message.success(`删除成功`)
        getList()
      })
    }
    function bianji(row) {
      state.form1 = JSON.parse(JSON.stringify(row))

      if (state.form1.endTime) {
        state.form1.endTime = formatTime(Number(state.form1.endTime), 'yyyy-MM-dd HH:mm:ss')
      }

      state.innerVisible2 = true
    }
    function handleEdit(row) {
      state.rowData = row
      state.rescueStartTime1 = formatTimestampToDateTime(row.recTime)
      state.flag = true
      state.operationNote = row.project
    }

    const editPro = () => {
      const timestamp1 =
        typeof state.rescueStartTime === 'string'
          ? new Date(state.rescueStartTime.replace(/\s+/, 'T')).getTime()
          : Number(state.rescueStartTime)
      const timestamp2 =
        typeof state.rescueStartTime1 === 'string'
          ? new Date(state.rescueStartTime1.replace(/\s+/, 'T')).getTime()
          : Number(state.rescueStartTime1)

      const params = {
        hospitalNumber: patCur.value?.hospitalNumber,
        patientIdent: patCur.value?.patientIdent,

        rescueTime: timestamp1,
        recTime: timestamp2,
        project: state.operationNote,
        id: state.rowData.id,
      }
      modifyRescue(params).then((res) => {
        getRescueData()
        state.flag = false
        state.operationNote = ''
        state.rescueStartTime1 = ''
      })
    }

    function handleRecordDel(row) {
      delRescue(row.id).then(() => {
        $message.success(`删除成功`)
        getRescueData()
      })
    }

    function formatTimestampToDateTime(timestamp) {
      const date = new Date(Number(timestamp))
      const pad = (num) => num.toString().padStart(2, '0')
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
        date.getDate(),
      )} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
    }
    function sure() {
      state.form.endTime = new Date()
      state.innerVisible = true
    }
    function submit() {
      if (!state.form.endTime) {
        $message.warning('抢救结束时间不能为空！')
        return
      }
      const timestamp1 =
        typeof state.rescueStartTime === 'string'
          ? new Date(state.rescueStartTime.replace(/\s+/, 'T')).getTime()
          : Number(state.rescueStartTime)
      const timestamp2 =
        typeof state.form.endTime === 'string'
          ? new Date(state.form.endTime.replace(/\s+/, 'T')).getTime()
          : Number(state.form.endTime)
      const now = new Date()

      const param = {
        hospitalNumber: patCur.value?.hospitalNumber,
        patientIdent: patCur.value?.patientIdent,

        patientName: patCur.value.patientName,
        bed: patCur.value?.bedNumber,
        startTime: timestamp1,

        rescueTime: timestamp1,
        //   diagnosis: zdIndex.value,

        timePointList: [now.getTime()],
      }
      const curParams = Object.assign(param, state.form, {
        endTime: timestamp2,
      })

      saveGeneral(curParams).then((res) => {
        if (res.data) {
          $message.success('提交成功')
          state.innerVisible = false
          state.form = { reason: '', result: '', rescuer: '', endTime: '' }
          stopRescue()
          getList()
          window.close()
        }
      })
    }

    function submit2() {
      const params = JSON.parse(JSON.stringify(state.form1))
      let timestamp1
      if (params.endTime) {
        timestamp1 =
          typeof params.endTime === 'string'
            ? new Date(params.endTime.replace(/\s+/, 'T')).getTime()
            : Number(params.endTime)
      }
      const obj = Object.assign(params, { endTime: timestamp1 })
      generalRecord(obj).then((res) => {
        if (res.data) {
          $message.success('编辑成功')
        }
        getList()
        state.innerVisible2 = false
      })
    }

    const collectHisData = (id) => {
      const timestamp1 =
        typeof state.rescueStartTime === 'string'
          ? new Date(state.rescueStartTime.replace(/\s+/, 'T')).getTime()
          : Number(state.rescueStartTime)
      const now = new Date()
      const param = {
        hospitalNumber: patCur.value?.hospitalNumber,
        patientIdent: patCur.value?.patientIdent,
        generalId: id,
        rescueTime: timestamp1,
        acquisitionFrequency: state.collectionFrequency,
        caijiren: shortName.value,
        timePointList: [now.getTime()],
      }
      collectHis(param).then((res) => {
        if (res.data) {
          queryHisData(id)
        }
      })
    }
    const saveGeneralData = () => {
      const timestamp1 =
        typeof state.rescueStartTime === 'string'
          ? new Date(state.rescueStartTime.replace(/\s+/, 'T')).getTime()
          : Number(state.rescueStartTime)

      const params = {
        hospitalNumber: patCur.value?.hospitalNumber,
        patientIdent: patCur.value?.patientIdent,

        startTime: timestamp1,
        endTime: '',
        createBy: shortName.value,
      }
      saveGeneral(params).then((res) => {
        state.Id = res.data.id
        collectHisData(res.data.id)
      })
    }

    const saveHisData = () => {
      const param = {
        createTime: state.rescueStartTime,
        caijiren: shortName.value,
        patientIdent: patCur.value.patientIdent,
      }
      saveHis(param).then((res) => {})
    }

    const queryHisData = (id) => {
      const timestamp1 =
        typeof state.rescueStartTime === 'string'
          ? new Date(state.rescueStartTime.replace(/\s+/, 'T')).getTime()
          : Number(state.rescueStartTime)

      const param = {
        hospitalNumber: patCur.value?.hospitalNumber,
        patientIdent: patCur.value?.patientIdent,
        rescueTime: timestamp1,
        generalId: id,
      }

      queryHis(param).then((res) => {
        if (res.data.length) {
          // 统一限制为20条最新数据
          const latestData = res.data.slice(-20)
          console.log('latestData', latestData)

          const timeData = latestData.map((val) => {
            const timeItem1 = format(new Date(val.createTime), 'HH:mm:ss')
            return timeItem1
          })
          state.youData = res.data[res.data.length - 1]
          updateTableData(latestData)
          // 转换图表数据格式
          const seriesData = {
            HR: latestData.map((item) => Number(item.ecg)),
            RR: latestData.map((item) => Number(item.rr)),
            SPO2: latestData.map((item) => Number(item.spo2)),
            ibpS: latestData.map((item) => Number(item.ibpS)),
            ibpD: latestData.map((item) => Number(item.ibpD)),
            NibpS: latestData.map((item) => Number(item.nibpS)),
            NibpD: latestData.map((item) => Number(item.nibpD)),
          }
          state.timePoints = timeData
          updateChartData(seriesData)
        }
        initMQTT()
      })
    }

    const initMQTT = () => {
      clearInterval(dataUpdateInterval.value)
      const interval = parseInt(state.collectionFrequency) * 1000

      dataUpdateInterval.value = setInterval(() => {
        if (state.isRescuing) {
          lishi()
        }
      }, interval)
    }

    const lishi = () => {
      collectHisData(state.Id)
    }

    const updateChartData = (data) => {
      if (chart.value) {
        const option = chart.value.getOption()
        // 遍历所有系列，按名称匹配数据
        option.series.forEach((series) => {
          if (data[series.name]) {
            series.data = data[series.name] // 直接绑定完整数据数组
          }
        })
        // 更新时间轴数据
        option.xAxis[0].data = state.timePoints

        chart.value.setOption(option, true)
      }
    }

    const updateTableData = (data) => {
      state.vitalData = data
      if (state.vitalData.length > 20) {
        state.vitalData = state.vitalData.slice(-20) // 取最后20条
      }
    }

    const toggleRescueMode = () => {
      if (state.isRescuing) {
        state.confirmDialogVisible = true
      } else {
        startRescue()
      }
    }

    const startRescue = () => {
      state.isRescuing = true

      startTimer()

      // 清空数据
      if (chart.value) {
        const option = chart.value.getOption()
        option.series.forEach((series) => {
          series.data = Array(20).fill(0)
        })
        chart.value.setOption(option)
      }
      state.vitalData = []
      state.operationRecords = []
    }

    const stopRescue = () => {
      state.isRescuing = false
      state.confirmDialogVisible = false
      clearInterval(timer.value)
      timer.value = null
      state.currentTime = '00:00:00'
    }

    const startTimer = () => {
      let seconds = 0
      timer.value = setInterval(() => {
        seconds++
        const hrs = Math.floor(seconds / 3600)
          .toString()
          .padStart(2, '0')
        const mins = Math.floor((seconds % 3600) / 60)
          .toString()
          .padStart(2, '0')
        const secs = (seconds % 60).toString().padStart(2, '0')
        state.currentTime = `${hrs}:${mins}:${secs}`
      }, 1000)
    }

    const handleFrequencyChange = () => {
      //  updateChart() // 更新图表
      // 重启数据更新定时器
      clearInterval(dataUpdateInterval.value)
      initMQTT()
    }

    const addActionOrMedicine = (med) => {
      const now = new Date()
      const timestamp2 =
        typeof state.rescueStartTime === 'string'
          ? new Date(state.rescueStartTime.replace(/\s+/, 'T')).getTime()
          : Number(state.rescueStartTime)

      const record = {
        project: med,
        hospitalNumber: patCur.value?.hospitalNumber,
        patientIdent: patCur.value?.patientIdent,

        rescueTime: timestamp2,
        recTime: now.getTime(),
      }

      addRescue(record).then((res) => {
        if (res.data) {
          $message.success('操作成功')
          getRescueData()
        }
      })
    }

    const cancel = () => {
      state.flag = false
      state.rescueStartTime1 = ''
      state.operationNote = ''
    }
    const newAdd = () => {
      const now = new Date()
      const timestamp2 =
        typeof state.rescueStartTime === 'string'
          ? new Date(state.rescueStartTime.replace(/\s+/, 'T')).getTime()
          : Number(state.rescueStartTime)
      const timestamp3 =
        typeof state.rescueStartTime1 === 'string'
          ? new Date(state.rescueStartTime1.replace(/\s+/, 'T')).getTime()
          : Number(state.rescueStartTime1)

      if (!state.operationNote.trim()) return
      const record = {
        project: state.operationNote,
        hospitalNumber: patCur.value?.hospitalNumber,
        patientIdent: patCur.value?.patientIdent,
        rescueTime: timestamp2,
        // recTime: now.getTime()
        recTime: timestamp3,
      }
      addRescue(record).then((res) => {
        if (res.data) {
          $message.success('操作成功')
          state.rescueStartTime1 = ''
          getRescueData()
        }
      })
      state.operationNote = ''
    }

    const getRescueData = () => {
      const timestamp2 =
        typeof state.rescueStartTime === 'string'
          ? new Date(state.rescueStartTime.replace(/\s+/, 'T')).getTime()
          : Number(state.rescueStartTime)
      const record = {
        hospitalNumber: patCur.value?.hospitalNumber,
        patientIdent: patCur.value?.patientIdent,
        rescueTime: '',
        recTime: timestamp2,
      }
      getRescue(record).then((res) => {
        state.operationRecords = res.data
      })
    }
    function permissionCheck() {
      //return roles.value.includes(window.nurseLeaderRole) || roles.value.includes('SUPER_ADMIN')
    }

    onMounted(() => {
      nextTick(() => initChart())
      initMQTT()
      startRescue()
    })

    onBeforeUnmount(() => {
      if (chart.value) {
        chart.value.dispose()
      }
      clearInterval(timer.value)
      clearInterval(dataUpdateInterval.value)
    })

    watch(
      // () => patCur.value,
      // (val) => {
      //   if (val) {
      //     saveGeneralData()

      //     getRescueData()
      //   }
      // },
      { immediate: true },
    )

    return {
      ...toRefs(state),
      permissionCheck,
      // roles,
      sure,
      editPro,
      handleDel,
      //  zd: zdIndex,
      submit,

      submit2,
      chartContainer,
      lishi,
      handleEdit,
      bianji,
      openLishi,
      gender,
      toggleRescueMode,
      stopRescue,
      handleFrequencyChange,
      addActionOrMedicine,
      formatTimestampToDateTime,
      newAdd,
      cancel,
      saveHisData,
      collectHisData,
      queryHisData,
      format,
      //patCur,
      shortName,
      handleRecordDel,
      formatTime,
    }
  },
})
</script>

<style lang="scss" scoped>
.flexBox {
  display: flex;
  justify-content: space-between;
  padding: 2px 8px;
  align-items: center;
  background-color: #fffbff;
  border-bottom: 1px solid #e4e4e4;
}

.rescue-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 15px;
  background-color: #f5f7fa;
}

.control-bar {
  display: flex;
  align-items: center;
  background: white;
  padding: 10px 15px;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 1px 4px rgb(0 0 0 / 10%);

  .patient-info {
    margin-left: 15px;
    font-weight: bold;

    .patient-id {
      color: #1565c0;
      margin-right: 10px;
    }

    .patient-name {
      // color: #1565c0;
      margin-right: 10px;
    }

    .patient-sex {
      margin-right: 12px;
      color: #666;
    }

    .patient-age {
      color: #666;
    }
  }

  .time-control {
    flex: 1;
    display: flex;
    align-items: center;
    margin-left: 30px;

    > * {
      margin-right: 10px;
    }

    .timer {
      font-family: Arial, sans-serif;
      font-size: 18px;
      font-weight: bold;
      min-width: 80px;
      color: #f00;
    }
  }

  .action-buttons {
    margin-left: auto;

    .history-btn {
      margin-left: 10px;
    }
  }
}

.main-content {
  display: flex;
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 4px rgb(0 0 0 / 10%);
  margin-bottom: 15px;

  .view-switch {
    position: absolute;
    left: 30px;
    top: 90px;
    z-index: 10;
  }
}

.chart-area {
  flex: 3;
  margin-top: 24px;

  .chart-container {
    height: 300px;
    width: 100%;
  }
}

.table-area {
  flex: 3;
  height: 300px;
  overflow-y: auto;
  margin-top: 30px;
}

.vital-signs {
  flex: 1;
  padding-left: 20px;
  border-left: 1px solid #eee;
  // display: grid;
  // grid-template-columns: 1fr 1fr;
  gap: 10px;
  align-content: start;

  .vital-card {
    background: #f9f9f9;
    border-radius: 4px;
    padding: 10px;
    text-align: center;
    margin: 8px 0;

    .vital-name {
      color: #666;
      font-size: 14px;
      margin-bottom: 5px;
    }

    .vital-value {
      font-weight: bold;
      font-size: 18px;
    }
  }
}

.operation-area {
  display: flex;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 4px rgb(0 0 0 / 10%);

  .action-buttons {
    width: 300px;
    margin-right: 10px;
    box-shadow: 0 1px 4px rgb(0 0 0 / 10%);

    .button-group {
      margin-bottom: 15px;

      .group-title {
        font-weight: bold;
        padding: 12px 16px;
        margin-bottom: 5px;
        border-bottom: 1px solid #e4e4e4;
        background-color: #fffbff;
        // background-color: #e4e4e4;
      }

      .group-titleSpe {
        font-weight: bold;
      }

      .el-button {
        margin: 3px 5px;
      }
    }
  }

  .record-form {
    margin-bottom: 10px;
    color: #999;
    padding: 8px 14px;

    .el-input {
      flex: 1;
      margin-right: 10px;
    }
  }

  .record-area {
    flex: 1;

    .record-title {
      font-weight: bold;
      margin-bottom: 10px;
    }

    .records-list {
      max-height: 300px;
      overflow-y: auto;
      border: 1px solid #eee;
      border-radius: 4px;

      .record-header {
        display: flex;
        padding: 5px 10px;
        background: #f5f5f5;
        font-weight: bold;
        border-bottom: 1px solid #eee;

        span {
          flex: 1;
        }
      }

      .record-item {
        display: flex;
        padding: 5px 10px;
        border-bottom: 1px solid #eee;
        cursor: pointer;
        align-items: center;

        &:hover {
          background-color: #f9f9f9;
        }

        .record-time {
          // flex: 0 0 80px;
          color: #666;
        }

        .record-action {
          // flex: 1;
        }

        span {
          flex: 1;
        }
      }

      .empty-record {
        padding: 20px;
        text-align: center;
        color: #999;
      }
    }
  }
}
</style>
